package com.zone.trigger.http;

import com.zone.domain.acticity.model.entity.*;
import com.zone.domain.acticity.model.valobj.ActivityOrderTraceTypeEnum;
import com.zone.domain.acticity.service.IActivityOrderPartakeService;
import com.zone.domain.acticity.service.IActivityOrderQuota;
import com.zone.domain.acticity.service.IActivitySkuProductService;
import com.zone.domain.acticity.service.armory.IActivitySkuArmory;
import com.zone.domain.award.model.entity.UserAwardRecordEntity;
import com.zone.domain.award.model.valobj.AwardStateEnum;
import com.zone.domain.award.service.IAwardService;
import com.zone.domain.credit.model.entity.UserCreditAdjustAmountEntity;
import com.zone.domain.credit.model.valobj.TradeNameEnum;
import com.zone.domain.credit.model.valobj.TradeTypeEnum;
import com.zone.domain.credit.service.IUserCreditAccountQuoteService;
import com.zone.domain.rebate.model.entity.UserBehaviorRebateOrderEntity;
import com.zone.domain.rebate.model.entity.UserRebateCreateOrderEntity;
import com.zone.domain.rebate.model.valobj.BehaviorTypeEnum;
import com.zone.domain.rebate.service.IBehaviorRebateService;
import com.zone.domain.strategy.model.entity.RaffleParamEntity;
import com.zone.domain.strategy.model.entity.RaffleResultEntity;
import com.zone.domain.strategy.service.IRaffleStrategy;
import com.zone.domain.strategy.service.armory.IStrategyArmory;
import com.zone.trigger.api.IRaffleActivityService;
import com.zone.trigger.api.dto.*;
import com.zone.types.exception.BizException;
import com.zone.types.model.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/2/25
 */
@CrossOrigin("${app.config.cross-origin}")
@RestController
@RequestMapping("/api/${app.config.api-version}/raffle/activity")
@DubboService(version = "1.0")
public class RaffleActivityController implements IRaffleActivityService {
    @Autowired
    private IActivitySkuArmory activitySkuArmory;
    @Autowired
    private IStrategyArmory strategyArmory;
    @Autowired
    private IActivityOrderPartakeService activityOrderPartakeService;
    @Resource
    private IRaffleStrategy raffleStrategy;
    @Autowired
    private IAwardService awardService;
    @Autowired
    private IBehaviorRebateService behaviorRebateService;
    @Autowired
    private IActivityOrderQuota activityOrderQuota;
    @Autowired
    private IActivitySkuProductService activitySkuProductService;
    @Autowired
    private IUserCreditAccountQuoteService userCreditAccountQuoteService;


    @Override
    @GetMapping("/armory")
    public Response<Boolean> armory(@RequestParam Long activityId) {
        // 活动库存装配
        activitySkuArmory.assembleActivitySkuStockCountByActivity(activityId);
        // 策略装配
        strategyArmory.assembleLotteryStrategyByActivity(activityId);
        return Response.success(true);
    }


    @Override
    @PostMapping("/draw")
    public Response<RaffleActivityDrawResponseDTO> draw(@RequestBody RaffleActivityDrawRequestDTO request) {
        // 参数校验
        if (Strings.isBlank(request.getUserId())) {
            throw new BizException("用户Id不能为空");
        }
        if (Objects.isNull(request.getActivityId())) {
            throw new BizException("活动Id不能为空");
        }
        // 创建用户参与单
        ActivityOrderPartakeEntity activityOrderPartakeEntity = new ActivityOrderPartakeEntity();
        activityOrderPartakeEntity.setUserId(request.getUserId());
        activityOrderPartakeEntity.setActivityId(request.getActivityId());
        UserRaffleOrderEntity userRaffleOrderEntity = activityOrderPartakeService.partTakeActivity(activityOrderPartakeEntity);
        // 执行抽奖策略抽奖
        RaffleParamEntity raffleParam = new RaffleParamEntity();
        raffleParam.setStrategyId(userRaffleOrderEntity.getStrategyId());
        raffleParam.setUserId(request.getUserId());
        RaffleResultEntity raffleResult = raffleStrategy.raffle(raffleParam);
        // 保存用户中奖记录
        UserAwardRecordEntity userAwardRecordEntity = new UserAwardRecordEntity();
        userAwardRecordEntity.setUserId(request.getUserId());
        userAwardRecordEntity.setActivityId(request.getActivityId());
        userAwardRecordEntity.setStrategyId(userRaffleOrderEntity.getStrategyId());
        userAwardRecordEntity.setOrderId(RandomStringUtils.randomNumeric(11));
        userAwardRecordEntity.setAwardId(raffleResult.getAwardId());
        userAwardRecordEntity.setAwardTitle(raffleResult.getAwardTitle());
        userAwardRecordEntity.setAwardTime(new Date());
        userAwardRecordEntity.setAwardState(AwardStateEnum.CREATE);
        userAwardRecordEntity.setAwardConfig(raffleResult.getAwardConfig());
        awardService.saveUserAwardRecord(userAwardRecordEntity);
        // 返回奖品信息
        RaffleActivityDrawResponseDTO raffleActivityDrawResponseDTO = new RaffleActivityDrawResponseDTO();
        raffleActivityDrawResponseDTO.setAwardId(raffleResult.getAwardId());
        raffleActivityDrawResponseDTO.setAwardTitle(raffleResult.getAwardTitle());
        raffleActivityDrawResponseDTO.setAwardIndex(raffleResult.getSort());
        return Response.success(raffleActivityDrawResponseDTO);
    }

    @PostMapping("/sign")
    @Override
    public Response<Boolean> sign(@RequestParam String userId) {
        UserRebateCreateOrderEntity userRebateCreateOrderEntity = new UserRebateCreateOrderEntity();
        userRebateCreateOrderEntity.setUserId(userId);
        userRebateCreateOrderEntity.setBehaviorTypeEnum(BehaviorTypeEnum.SIGN);
        String nowDateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        userRebateCreateOrderEntity.setOutBusinessNo(nowDateStr);
        behaviorRebateService.createUserBehaviorOrder(userRebateCreateOrderEntity);
        return Response.success(true);
    }

    /**
     * 判断用户当天是否签到
     *
     * @param userId 用户id
     * @return
     */
    @PostMapping("/is_user_sign")
    @Override
    public Response<Boolean> isUserSign(@RequestParam String userId) {
        // 获取当天用户签到流返利单
        List<UserBehaviorRebateOrderEntity> userBehaviorRebateOrderList = behaviorRebateService.queryUserBehaviorRebateOrderList(userId, BehaviorTypeEnum.SIGN, LocalDate.now());
        return Response.success(CollectionUtils.isNotEmpty(userBehaviorRebateOrderList));
    }

    /**
     * 判断用户当天是否签到
     *
     * @param requestDTO
     * @return
     */
    @PostMapping("/query_user_activity_account")
    @Override
    public Response<UserActivityAccountResponseDTO> queryUserActivityAccount(@RequestBody UserActivityAccountRequestDTO requestDTO) {
        // 获取当天用户签到流返利单
        RaffleActivityAccountEntity activityAccountEntity = activityOrderQuota.queryUserActivityAccount(requestDTO.getUserId(), requestDTO.getActivityId());
        UserActivityAccountResponseDTO userActivityAccountResponseDTO = new UserActivityAccountResponseDTO();
        userActivityAccountResponseDTO.setTotalCount(activityAccountEntity.getTotalCount());
        userActivityAccountResponseDTO.setTotalCountSurplus(activityAccountEntity.getTotalCountSurplus());
        userActivityAccountResponseDTO.setDayCount(activityAccountEntity.getDayCount());
        userActivityAccountResponseDTO.setDayCountSurplus(activityAccountEntity.getDayCountSurplus());
        userActivityAccountResponseDTO.setMonthCount(activityAccountEntity.getMonthCount());
        userActivityAccountResponseDTO.setMonthCountSurplus(activityAccountEntity.getMonthCountSurplus());
        return Response.success(userActivityAccountResponseDTO);
    }

    @GetMapping("/query_sku_product_list")
    @Override
    public Response<List<SkuProductResponseDTO>> querySkuProductList(@RequestParam Long activityId) {
        List<SkuProductEntity> skuProductEntities = activitySkuProductService.querySkuProductList(activityId);
        // 过滤金额不为null的sku
        skuProductEntities = skuProductEntities.stream()
                .filter(skuProductEntity -> Objects.nonNull(skuProductEntity.getProductAmount()))
                .collect(Collectors.toList());
        List<SkuProductResponseDTO> responseDTOList = skuProductEntities.stream().map(skuProductEntity -> {
            SkuProductResponseDTO skuProductResponseDTO = new SkuProductResponseDTO();
            skuProductResponseDTO.setSku(skuProductEntity.getSku());
            skuProductResponseDTO.setActivityId(skuProductEntity.getActivityId());
            skuProductResponseDTO.setActivityCountId(skuProductEntity.getActivityCountId());
            skuProductResponseDTO.setStockCount(skuProductEntity.getStockCount());
            skuProductResponseDTO.setStockCountSurplus(skuProductEntity.getStockCountSurplus());
            skuProductResponseDTO.setProductAmount(skuProductEntity.getProductAmount());

            SkuProductEntity.ActivityCount countEntity = skuProductEntity.getActivityCount();
            SkuProductResponseDTO.ActivityCount activityCount = new SkuProductResponseDTO.ActivityCount();
            activityCount.setTotalCount(countEntity.getTotalCount());
            activityCount.setDayCount(countEntity.getDayCount());
            activityCount.setMonthCount(countEntity.getMonthCount());
            skuProductResponseDTO.setActivityCount(activityCount);
            return skuProductResponseDTO;
        }).collect(Collectors.toList());
        return Response.success(responseDTOList);
    }


    @PostMapping("/credit_pay_exchange_sku")
    @Override
    public Response<Boolean> creditPayExchangeSku(@RequestBody SkuProductOrderRequestDTO request) {
        // 活动额度充值
        ActivityOrderCreateEntity activityOrderCreateRequest = new ActivityOrderCreateEntity();
        activityOrderCreateRequest.setUserId(request.getUserId());
        activityOrderCreateRequest.setSku(request.getSku());
        activityOrderCreateRequest.setOutBusinessNo(RandomStringUtils.randomNumeric(12));
        activityOrderCreateRequest.setOrderTraceTypeEnum(ActivityOrderTraceTypeEnum.PAY);
        ActivityCreatedOrderResponseEntity createdOrderResponse = activityOrderQuota.doOrder(activityOrderCreateRequest);

        // 用户积分扣减
        UserCreditAdjustAmountEntity creditAdjustAmountEntity = new UserCreditAdjustAmountEntity();
        creditAdjustAmountEntity.setUserId(request.getUserId());
        creditAdjustAmountEntity.setTradeName(TradeNameEnum.ACTIVITY_ORDER_REDEEM_AWARD.getCode());
        creditAdjustAmountEntity.setTradeTypeEnum(TradeTypeEnum.REVERSE);
        creditAdjustAmountEntity.setAmount(createdOrderResponse.getProductAmount());
        creditAdjustAmountEntity.setOutBusinessNo(createdOrderResponse.getOutBusinessNo());
        userCreditAccountQuoteService.adjustAmount(creditAdjustAmountEntity);
        return Response.success(true);
    }
}
